package edu.jhmi.tools.omssa_gui;

/**
 * @author Ravi Tharakan
 * @author Lennart Martens
 *
 */

import java.util.*;
import java.io.*;

/**
 * This class takes care of starting the formatdb Process.
 *
 */

public class FormatdbProcessBuilder extends OmssaguiProcessBuilder {

    /**
     * The FASTA sequence database file to process.
     */
    private File iDatabaseFile = null;

    private boolean isCancelled = false;

    /**
     * Constructor.
     * 
     * @param aDatabaseFile File with the DB file to be formatted
     * @param aOMSSA_location File with the OMSSA location (used to find formatdb.exe)
     */
    public FormatdbProcessBuilder(File aDatabaseFile, File aOMSSA_location) {
        // check if mac or windows
        checkOperatingSystem();
        // full path to executable
        process_name_array.add(aOMSSA_location.getAbsolutePath() + "/formatdb");
        // add arguments for database file
        process_name_array.add("-i");
        process_name_array.add(aDatabaseFile.getName());
        process_name_array.trimToSize();
        pb = new ProcessBuilder(process_name_array);
        pb.directory(aDatabaseFile.getParentFile());
        // set error out and std out to same stream
        pb.redirectErrorStream(true);
        iDatabaseFile = aDatabaseFile;
    }

    /**
     * Checks if formatdb has already been run on this file
     *
     * @return boolean returns true if formatdb has been run
     */

    public boolean needsFormatting() {
        boolean result = true;
        String[] list = iDatabaseFile.getParentFile().list();
        // Get the filename.
        String name = iDatabaseFile.getName();

        // Find all three processed files.
        boolean phr = false;
        boolean pin = false;
        boolean psq = false;
        for (int i = 0; i < list.length; i++) {
            String s = list[i];
            if (s.equals(name + ".phr")) {
                phr = true;
            }
            if (s.equals(name + ".pin")) {
                pin = true;
            }
            if (s.equals(name + ".psq")) {
                psq = true;
            }
        }

        if (phr&&pin&&psq) {
            result = false;
        }

        return result;
    }

    /**
     * Starts the process of a process builder, gets the inputstream from the
     * process and shows it in a JTextArea. Does not close until the process
     * is completed.
     *
     * @return Process the process started.
     */
    public void startProcess() {
        super.startProcess();
        if(isCancelled) {
            // remove incomplete db index files.
            File tempFile = new File(iDatabaseFile.getAbsolutePath()+".phr");
            deleteFile(tempFile);
            tempFile = new File(iDatabaseFile.getAbsolutePath()+".pin");
            deleteFile(tempFile);
            tempFile = new File(iDatabaseFile.getAbsolutePath()+".psq");
            deleteFile(tempFile);
        }
    }

    public void endProcess() {
        isCancelled = true;
        super.endProcess();
    }

    private void deleteFile(File aFile) {
        int count = 0;
        boolean deleteOK = true;
        while(!aFile.delete()) {
            count++;
            if(count > 5) {
                deleteOK = false;
                break;
            }
        }
        if(!deleteOK) {
            System.err.println(" *** Failed to deleted file " + aFile.getAbsolutePath() + "! ***");
        }
    }
}
